<template>
  <common-edit-dialog
      title="全局配置"
      :visible.sync="dialogShow"
      @cancel="cancel"
      @submit="submitForm"
      :width="'900px'"
  >
    <div class="report-component-wrap">
      <div class="group-header-wrap">
        <div class="filter-header">
          <div class="filter-header-title">筛选器</div>
          <!--          <i class="iconfont icon-tianjia" @click="add"></i>-->
          <commonIcon iconName="icon-tianjia" iconType="icon" @click="add" iconSize="12"></commonIcon>
        </div>
        <!-- 列表 -->
        <div class="filter-list">
          <div class="filter-list-item"
               :class="isClickIndex === index ? 'isActive' : ''"
               :style="{'--theme-color': systemInfo.theme}"
               @click.stop="handleMenuClick(item, index)"
               v-for="(item,index) in filterData">
            <common-carousel-text
                class="filter-item-name"
                :content="item.name"
                :index="index"
                :font-size="12">
            </common-carousel-text>
            <!--            <i class="el-icon-delete" @click="del(index)"></i>-->
            <commonIcon iconName="el-icon-delete" iconType="icon" iconSize="14" @click="del(index)"
                        isStyle></commonIcon>
          </div>
        </div>

        <div></div>
      </div>
      <div class="filter-content">
        <el-form ref="form" :model="filterData[isClickIndex]" :rules="rules" label-width="65px">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="组件名称">
                <common-input v-model="filterData[isClickIndex].name" :maxlength="16" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <common-group-title title="筛选配置"></common-group-title>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="36px">
                <template>
                  <span>筛选类型</span>
                  <el-select
                      class="el-select-formDateType"
                      placeholder="请选择"
                      filterable
                      clearable
                      v-model="filterData[isClickIndex].filterType"
                      @change="changeFilterType">
                    <el-option
                        v-for="(items, index) in filterTypeList"
                        :key="items.label"
                        :label="items.label"
                        :value="items.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="filterData[isClickIndex].filterType === 'dateFilter'">
              <el-form-item label-width="36px">
                <template>
                  <el-radio-group v-model="filterData[isClickIndex].timeConfig" @change="changePicker">
                    <el-radio label="datetime">日期时间</el-radio>
                    <el-radio label="datetimeRange">日期时间范围</el-radio>
                  </el-radio-group>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="filterData[isClickIndex].filterType === 'dateFilter'">
              <el-form-item label-width="36px">
                <template>
                  <span>时间类型</span>
                  <el-select
                      class="el-select-formDateType"
                      placeholder="请选择"
                      v-model="filterData[isClickIndex].formDataType">
                    <el-option
                        v-for="(items, index) in formDataType"
                        :key="items.label"
                        :label="items.label"
                        :value="items.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <common-group-title title="联动组件"></common-group-title>
            </el-col>
            <el-col :span="24">
              <div class="filter-content-checkBox">
                <template>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" size="mini"
                               @change="handleCheckAllChange">全选
                  </el-checkbox>
                  <div class="checkbox-list">
                    <div class="checkbox-item" v-for="(item, i) in filterData[isClickIndex].analysisList">
                      <el-checkbox v-model="item.isCheck" size="mini" @change="handleChecked(item ,i)"></el-checkbox>
                      <common-carousel-text
                          class="checkbox-item-name"
                          :content="item.chartName"
                          :index="i"
                          :key-word="i"
                          :fontSize="14">
                      </common-carousel-text>
                      <el-select placeholder="请选择" v-model="item.selectVarName" @change="handleSelect(i,'0')">
                        <el-option
                            v-for="(ds, index) in variableDataByType(item.variableData, filterData[isClickIndex].filterType)"
                            :key="ds.id"
                            :label="ds.name"
                            :value="ds.name"
                        ></el-option>
                      </el-select>
                      <el-select
                          style="margin-left: 6px"
                          placeholder="请选择"
                          v-model="item.selectVarName2"
                          v-if="filterData[isClickIndex].timeConfig === 'datetimeRange'"
                          @change="handleSelect(i,'1')">
                        <el-option
                            v-for="(ds, index) in item.variableData"
                            :key="ds.id"
                            :label="ds.name"
                            :value="ds.name"
                        ></el-option>
                      </el-select>
                    </div>
                  </div>
                </template>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>

    </div>
  </common-edit-dialog>
</template>

<script>
import { _deepClone, guid } from '@/utils'
import { mapGetters } from 'vuex'
import commonIcon from '@/components/CommonIcon'

export default {
  name: 'filterDialog',
  props: {
    analysisList: {
      type: Array,
      default: () => []
    },
    tempOption: {
      type: Array,
      default: () => []
    }
  },
  components: {
    commonIcon
  },
  data() {
    return {
      dialogShow: false,
      isClickIndex: 0,
      filterData: [{
        id: guid(),
        name: '默认筛选器',
        filterType: 'dateFilter',
        timeConfig: 'datetime',
        formDataType: '{y}-{m}-{d} {h}:{i}:{s}',
        analysisList: [],
        content: null
      }],
      checkAll: false,
      isIndeterminate: false,
      globalList: [],//全局变量
      rules: {},
      formDataType: [
        { label: '年-月-日 时:分:秒', value: '{y}-{m}-{d} {h}:{i}:{s}' },
        { label: '年-月-日 时:分', value: '{y}-{m}-{d} {h}:{i}' },
        { label: '年-月-日 时', value: '{y}-{m}-{d} {h}' },
        { label: '年-月-日', value: '{y}-{m}-{d}' },
        { label: 'UTC时间类型', value: 'UTC' },
        { label: '时间戳类型', value: 'timeStamp' }
      ],
      filterTypeList: [
        { label: '时间筛选', value: 'dateFilter' },
        { label: '输入框筛选', value: 'inputFilter' }
      ]
    }
  },
  watch: {
    analysisList(val) {
      this.init(val)
    }
  },
  computed: {
    ...mapGetters(['systemInfo'])
  },
  methods: {
    showDialog() {
      this.checkAll = false
      this.isIndeterminate = false
      this.dialogShow = true
      this.init(this.analysisList)
    },
    /**
     * 初始化处理数据
     */
    init(val) {
      if (this.tempOption.length) {
        this.filterData = _deepClone(this.tempOption)
        this.filterData.forEach(f => {
          val.forEach(v => {
            if (!f.analysisList.find(ds => ds.id === v.id)) {
              f.analysisList.push({
                ...v,
                isCheck: false,
                selectVarType: ''
              })
            } else {
              f.analysisList.find(ds => ds.id === v.id).variableData = v.variableData
            }
          })
        })

      } else {
        this.filterData = [{
          id: guid(),
          name: '默认筛选器',
          filterType: 'dateFilter',
          timeConfig: 'datetime',
          analysisList: [],
          formDataType: '{y}-{m}-{d} {h}:{i}:{s}',
          content: ''
        }]
        this.isClickIndex = 0
        this.setVariableData(this.analysisList)
      }
      this.setCheckAllStatus()
    },

    /**
     * 添加筛选器
     */
    add() {
      this.filterData.push({
        id: guid(),
        name: '默认筛选器',
        filterType: 'dateFilter',
        timeConfig: 'datetime',
        formDataType: '{y}-{m}-{d} {h}:{i}:{s}',
        analysisList: this.analysisList.reduce((r, c) => {
          r.push({
            ...c,
            isCheck: false,
            selectVarType: ''
          })
          return r
        }, []),
        content: null,
      })
      // this.isClickIndex++
    },
    
    variableDataByType(data, type) {
      let typeList = type === 'dateFilter' ? ['date'] : ['string', 'number']
      let variable = data ? data : []
      return variable.filter(f => typeList.includes(f.type))
    },

    /**
     * 删除筛选器
     * @params index
     */
    del(index) {
      if (this.filterData.length === 1) {
        return this.$GlobalErrorConfirm('删除失败', '至少有一个默认筛选器！')
      }
      if (this.isClickIndex >= index && index !== 0 || this.isClickIndex === this.filterData.length - 1) {
        this.isClickIndex = this.isClickIndex - 1
      }
      this.filterData.splice(index, 1)
    },
    changeFilterType(val) {
        this.filterData[this.isClickIndex].timeConfig = val === 'dateFilter' ? 'datetime' : ''
        this.filterData[this.isClickIndex].formDataType =  val === 'dateFilter' ? '{y}-{m}-{d} {h}:{i}:{s}' : ''
    },
    /**
     * 单选框事件
     * @params val
     */
    changePicker(val) {
      // this.filterData[this.isClickIndex].analysisList.map(item => item.selectVarName2 = '{y}-{m}-{d} {h}:{i}:{s}')
    },
    /**
     * 切换筛选器
     * @params item
     * @params index
     */
    handleMenuClick(item, index) {
      this.isClickIndex = index
      // console.log('父')
      this.setCheckAllStatus()
    },
    /**
     * 更换全选状态
     */
    setCheckAllStatus() {
      if (this.filterData[this.isClickIndex].analysisList.length) {
        let length = this.filterData[this.isClickIndex].analysisList.filter(f => !f.isCheck).length
        this.checkAll = length === 0
        this.isIndeterminate = length !== this.filterData[this.isClickIndex].analysisList.length && !this.checkAll
      }
    },
    /**
     * 全选
     * @param val
     */
    handleCheckAllChange(val) {
      this.checkAll = val
      this.filterData[this.isClickIndex].analysisList.map(item => item.isCheck = val)
    },
    /**
     * 单选
     * @param item
     * @param i
     */
    handleChecked(item, i) {
      this.setCheckAllStatus()
    },
    /**
     * 下拉框选中事件
     */
    handleSelect(i, index) {
      let data = this.filterData[this.isClickIndex].analysisList[i]
      if (index === '0') {
        data.selectVarType = data.variableData.find(f => f.name === data.selectVarName).type
      } else {
        data.selectVarType2 = data.variableData.find(f => f.name === data.selectVarName2).type
      }
    },
    /**
     * 确定
     */
    submitForm() {
      // this.cancel()
      let msg
      if (!this.analysisList.length) {
        msg = '没有联动组件，请先拖入报表组件！'
      } else {
        this.filterData.forEach(item => {
          item.analysisList.forEach(f => {
            if (f.isCheck && item.timeConfig === 'datetimeRange' && !f.selectVarName2) {
              msg = '类型为时间范围时，选中的联动组件中需要选择2个变量，请检查筛选器中是否选择正确！'
            }
          })
        })
      }
      if (msg) return this.$GlobalErrorConfirm('添加失败', msg)

      this.dialogShow = false
      this.$emit('setFilterConfig', this.filterData)
    },
    /**
     * 关闭弹窗
     */
    cancel() {
      this.dialogShow = false
      this.checkAll = false
      this.isIndeterminate = false
    },
    /**
     *
     */
    setVariableData(val) {
      this.filterData.forEach(f => {
        f.analysisList = val.reduce((r, c) => {
          r.push({
            ...c,
            isCheck: false,
            selectVarType: ''
          })
          return r
        }, [])
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .global-common-edit-dialog-body {
  overflow: hidden;
}

.report-component-wrap {
  display: flex;
  width: 100%;
  height: 100%;

  .group-header-wrap {
    width: 160px;
    border-right: 1px solid #eee;
    box-sizing: border-box;
    height: 400px;

    .filter-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-right: 12px;

      .icon-tianjia {
        font-size: 12px;
        cursor: pointer;
      }
    }

    .filter-list {
      margin-top: 12px;
      height: calc(100% - 32px);
      overflow-y: scroll;
      overflow-x: hidden;

      .filter-list-item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 28px;
        padding-left: 12px;
        padding-right: 4px;
        border-left: 2px solid transparent;
        cursor: pointer;

        .filter-item-name {
          width: calc(100% - 20px);
        }

        .el-icon-delete {
          opacity: 0;
          transition: all 0.3s;
        }

        &:hover {
          .el-icon-delete {
            opacity: 1;
          }
        }
      }
    }

    .isActive {
      border-left: 3px solid var(--theme-color) !important;
      background: #e5f3fe;
      color: var(--theme-color);
    }
  }

  .filter-content {
    padding-left: 12px;
    box-sizing: border-box;
    width: calc(100% - 160px);
    height: 400px;
    overflow-y: scroll;
    overflow-x: hidden;

    .el-select-formDateType {
      width: 200px;
      margin-left: 6px;
    }

    .filter-content-checkBox {
      margin-left: 36px;
    }

    .checkbox-list {

      .checkbox-item {
        margin-top: 12px;
        display: flex;
        align-items: center;


        .checkbox-item-name {
          width: 60px !important;
          margin: 0 12px;
          cursor: pointer;
        }

        .el-select {
          width: 200px;
        }
      }

    }
  }

}
</style>
